# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup


class ImageData(object):
    def __init__(self):
        self.url = "https://sc.chinaz.com/tupian/dongwutupian.html"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
        }

    # 发起请求
    def get_data_index(self):
        response = requests.get(self.url,  headers=self.headers)
        response.encoding = "utf-8"
        if response.status_code == 200:
            return response.text
        else:
            return None

    # 解析数据
    def parse_data(self, response):
        soup = BeautifulSoup(response, "lxml")
        data_list = soup.find_all("img", class_="lazy")
        for data in data_list:
            title = data.get("alt")
            image = "https:" + data.get("data-original")
            self.save_data(title, image)

    # 保存数据
    def save_data(self, title, image):
        with open("./images/" + title + ".jpg", "wb") as f:
            resp = requests.get(image).content
            f.write(resp)
            print(f"{title}:保存成功")

    # 实现业务
    def main(self):
        response = self.get_data_index()
        self.parse_data(response)
        # print(response)


if __name__ == '__main__':
    images = ImageData()
    images.main()
